package com.wgzx.modbus.entity;

import com.wgzx.modbus.constant.FunctionCode;
import com.wgzx.modbus.constant.ModbusErrors;
import io.netty.buffer.ByteBuf;
import lombok.Getter;

@Getter
public abstract class ModbusRsp extends PduFunc {

    protected short exceptionCode;
    protected String exceptionMessage;

    public ModbusRsp(FunctionCode funcCode) {
        super(funcCode);
    }

    /**
     * 解码正确的modbus响应消息
     *
     * @param buffer
     */
    public abstract void decode(ByteBuf buffer);

    /**
     * 解码错误的modbus响应消息
     *
     * @param buffer
     */
    public void decodeError(ByteBuf buffer) {
        exceptionCode = buffer.readUnsignedByte();
        this.setExceptionMessage(exceptionCode);
    }

    protected void setExceptionMessage(short exceptionCode) {
        this.exceptionMessage = ModbusErrors.get(exceptionCode) != null ? ModbusErrors.get(exceptionCode) : "UNDEFINED ERROR";
    }
}
